package base.auth;

import base.standard.constant.ErrorCode;
import base.standard.exception.SimpleException;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.lang3.time.DateUtils;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Jwt util
 *
 * @description:
 * @author: cyj
 * @date 2020 -10-21 20:28:25
 */
public class JwtUtil {
    /**
     * SECRET 密钥
     */
    public static final String SECRET = "cyj:simple:1.0";

    /**
     * Create token string
     *
     * @param loginId    login id
     * @param expireTime expire time
     * @return the string
     * @description: 生成 token
     */
    public static String createToken(String loginId, int expireTime) {
        Map<String, Object> header = new HashMap<>(10);
        header.put("alg", "HS256");
        header.put("typ", "JWT");
        String token = null;
        try {
            token = JWT.create()
                    .withHeader(header)
                    .withClaim("loginId", loginId)
                    .withSubject("token")
                    // 签名时间
                    .withIssuedAt(new Date())
                    //过期时间
                    .withExpiresAt(DateUtils.addSeconds(new Date(), expireTime))
                    .sign(Algorithm.HMAC256(SECRET));
        } catch (UnsupportedEncodingException e) {
            throw new SimpleException(ErrorCode.TOKEN_CREATE_ERROR);
        }
        return token;
    }

    /**
     * Verify token map
     *
     * @param token token
     * @return the map
     * @description: 解密token, 如果过期抛异常
     */
    public static Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            throw new SimpleException(ErrorCode.TOKEN_EXPIRE);
        }
        return jwt.getClaims();
    }

    /**
     * Parse token map
     *
     * @param token token
     * @return the map
     * @description: 解密token
     */
    public static Map<String, Claim> parseToken(String token) {
        DecodedJWT decodedJwt = JWT.decode(token);
        return decodedJwt.getClaims();
    }
}
